<template>
    <div style="background: #f9f3ed;overflow: hidden;height:100vh;max-height: 100vh;margin:0 auto;max-width: 1000px;">
        <!-- <div class="ProductQuote"> -->
        <ProductQuote :product="productInfo" :preferredArea="preferredArea" :isQuoteVisible="false" :isFloating="true"
            :isBuy="false" :countdownTime="countdownConfig" :productItems="productItems" />
        <!-- </div> -->
        <!-- <TencentSpeech /> -->

        <!-- 对话区 -->
        <div class="bg-bg-right" style="">
            <div class=" p-2 pb-1">
                <!-- 增加一个悬浮与顶部的推出按钮,按钮透明,只出现退出两个文字 -->
                <div class="flex items-center">
                    <el-popover placement="right" title="基础设置" width="340" trigger="click" @hide="PopoverHide">
                        <div>
                            <div class="flex items-center justify-between">
                                <span>语音播放</span><el-switch v-model="isRead" @change="setUserCookie('isRead', isRead)"
                                    active-text="是" inactive-text="否"></el-switch>
                            </div>
                            <div class="flex items-center justify-between mt10">

                                <span>播放速度</span>
                                <el-radio-group v-model="speed" size="mini" @input="setSpeed">
                                    <el-radio-button label="慢速"></el-radio-button>
                                    <el-radio-button label="正常"></el-radio-button>
                                    <el-radio-button label="快速"></el-radio-button>
                                    <el-radio-button label="极速"></el-radio-button>
                                </el-radio-group>
                            </div>
                            <el-divider content-position="right">下方配置：修改后会自动更新页面</el-divider>

                            <div class="flex items-center justify-between mt10">

                                <span>文字大小</span>
                                <el-input-number v-model="fontSize" @change="fontSizeChange" :min="14" :max="20"
                                    label="文字大小"></el-input-number>
                            </div>
                            <div class="flex items-center justify-between mt10">

                                <span>文本间距</span>
                                <el-input-number v-model="fontLine" @change="fontLineChange" :min="1" :max="2.5"
                                    :step="0.5" label="文本间距"></el-input-number>
                            </div>

                            <el-divider content-position="right">清除本次扫码信息</el-divider>

                            <div class="flex items-center justify-between">
                                <span>账号信息</span>
                                <el-button type="text" @click="setData"
                                    style="background: transparent;color: #8a5a52;"><i
                                        class="el-icon-switch-button  ml-2"
                                        style="font-size: 20px;"></i>退出账号</el-button>
                            </div>
                        </div>
                        <el-button type="text" slot="reference" style="background: transparent;color: #8a5a52;"><i
                                class="el-icon-setting  ml-2" style="font-size: 20px;"></i></el-button>
                    </el-popover>
                    <div class=" ml-2">
                        <span class="text-sm text-secondary">皮肤问题深度解析</span>
                        <span class="text-sm text-secondary ml-2"></span>
                    </div>

                </div>
                <!-- <div class="">
                    <h1 class="text-4xl font-bold text-primary mb-2" @click="upLocalUserInfo()">美容顾问</h1>
                    <p class="text-sm text-secondary">获取个性化建议，焕活肌肤光彩。</p>
                </div> -->
            </div>
            <!-- <el-button @click="upQuote({ CID: '', PID: '11' })">测试</el-button> -->

            <div class="wendaItem">
                <!-- <wendaItem height="100%" :isLogo="true" subtitle="我是您的美容顾问，可以向我咨询任何问题。"
                    api="/dev-api/demo/deepseek/customerAsk" :isRead="false" readText="我是您的美容顾问，可以向我咨询任何问题。"
                    inputPadd="0 10px" themeColor="#8a5a52" :isNewConvo="false" 
               :isSpeech="true" isSpeechType="tencent" 是否启用语音和语音使用本地还是腾讯 -->
                <wendaItem v-if="agentId" height="100%" :isLogo="true" subtitle="我是您的美容顾问，可以向我咨询任何问题。"
                    :assisId="agentId" :quesCarry="quesCarry" :isRead="isRead" readText="我是您的美容顾问，可以向我咨询任何问题。"
                    inputPadd="0 10px" themeColor="#eb87a2" :isNewConvo="false" @product-info-updated="upQuote"
                    :hotQues="hotQuesList" @hotQues-click="addClickHotQues" :isSpeech="false" isSpeechType="tencent" />
            </div>
        </div>

        <!-- 用户信息设置弹窗 -->
        <el-drawer title="携带信息" :visible.sync="drawerVisible" direction="rtl" size="40%" class="beauty-dialog">
            <div style="padding: 20px;">
                <el-form :model="quesCarry" label-position="top">
                    <el-form-item label="实际发送格式(前置条件)">
                        <el-input type="textarea" :rows="6"
                            placeholder="用户提问：{quesStr}. 首次携带：{firstData}. 始终携带：{alwaysData}. 实际问答中根据用户的意向调整推荐产品"
                            v-model="quesCarry.format">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="首次提问携带信息">
                        <el-input type="textarea" :rows="10"
                            placeholder="产品信息：【名称:'',价格:'',主要功能:''】\n\n历史购买：【名称:'',价格:'',主要功能:''】\n\n"
                            v-model="quesCarry.first">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="持续携带信息">
                        <el-input type="textarea" :rows="6" placeholder="用户关键信息：【年龄：''，性别：''，年龄段：''，消费金额：''】"
                            v-model="quesCarry.always">
                        </el-input>
                    </el-form-item>
                </el-form>
                <div style="margin-top: 20px; text-align: right;">
                    <el-button type="warning" @click="upUserInfo">彻底重置</el-button>
                    <el-button @click="drawerVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveUserInfo">保存</el-button>
                </div>
            </div>
        </el-drawer>

    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { listCustomer, getCustomerByOpenId, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/demo/customer";
import { listZhProduct, listProduct, getProduct } from "@/api/demo/product"; // 产品信息
import { listZhCertification, listCertification } from "@/api/demo/certification"; // 权威认证
import { listZhCombo, listCombo, getCombo } from "@/api/demo/combo"; // 套装
import { listZhHistory, listHistory } from "@/api/demo/history"; // 历史记录
import { listComboByArticleId } from "@/api/demo/combo"; // 根据文章ID获取套装信息
import { listAiHotNoScope, updateAiHot } from "@/api/demo/ai/hot"; // 获取热门问题

import { listAILibrary } from "@/api/demo/library"; // 案例

import wendaItem from '@/views/components/wendaItem.vue';
import ProductQuote from '../components/ProductQuote.vue'

import { getManageKey } from "@/api/demo/management";

import TencentSpeech from '@/components/Tencent/TencentSpeech.vue'

export default {
    name: 'BeaurceQuestion',
    components: { wendaItem, ProductQuote, TencentSpeech },
    ...mapGetters(["user"]),
    data() {
        return {
            baseApi: process.env.VUE_APP_BASE_API,

            agentId: null,
            // 用户信息抽屉显示控制
            drawerVisible: false,
            // 用户信息表单  
            quesCarry: {
                format: `本次提问不需要做任何多余回答，后续我会以客户身份向你咨询。\n如果有新的产品或套餐要推荐，同时可推荐一个套餐和多个商品，按以下格式追加到回答，以便我通过正则查找，格式：<#$&{"CID":"1","PID":"1"}#$&>\nCID：套餐id，可以为空字符串""，表示不推荐套餐。\nPID：单品id，多个用逗号分隔，可以为空字符串""，表示不推荐单品。\nCID / PID同时只存在一个，CID优先级更高。\n实际问答中根据用户的意向调整推荐产品。\n用户提问：{quesStr}.\n始终携带：{alwaysData}.\n首次携带：{firstData}.\n`,
                first: "",
                always: "",
            },
            // 1. 套装基本信息
            productInfo: {
                // name: '焕颜保湿护肤套装',
                // description: '包含洁面乳、精华液、保湿霜和面膜，专为敏感肌肤设计，深层滋养，焕发肌肤活力',
                // image: require('@/assets/images/mr/bann/banner (4).jpg'), // 主图
                // originalPrice: 1299, // 原价
                // currentPrice: 699,   // 现价
                // stock: 15,           // 剩余库存
                // gifts: ['化妆棉1包', '小样套装', '专属化妆包'] // 赠品
            },

            // 2. 优惠地区
            preferredArea: '小店区',

            // 3. 倒计时配置（初始时间）
            countdownConfig: {
                days: 1,    // 天
                hours: 12,  // 时
                minutes: 30,// 分
                seconds: 45 // 秒
            },

            // 4. 产品列表（套装包含的单品）
            productItems: [
                // {
                //     id: 1,
                //     name: '氨基酸温和洁面乳',
                //     specs: '100ml / 深层清洁 / 温和不刺激',
                //     price: 199,
                //     image: 'https://picsum.photos/100/100?random=11'
                // },
                // {
                //     id: 2,
                //     name: '玻尿酸保湿精华液',
                //     specs: '30ml / 补水锁水 / 提亮肤色',
                //     price: 329,
                //     image: 'https://picsum.photos/100/100?random=12'
                // },
                // {
                //     id: 3,
                //     name: '修护保湿霜',
                //     specs: '50g / 锁水保湿 / 修护屏障',
                //     price: 269,
                //     image: 'https://picsum.photos/100/100?random=13'
                // },
                // {
                //     id: 4,
                //     name: '焕颜修护面膜（5片装）',
                //     specs: '补水滋养 / 舒缓修护',
                //     price: 199,
                //     image: 'https://picsum.photos/100/100?random=14'
                // }
            ],
            CustomerInfo: null,
            // 产品数据变量
            proYuanhu: [],
            proJiaju: [],
            anli: [],
            auth: [],
            cuxiao: [],
            history: [],
            hotQuesList: [],

            isRead: true,
            speed: 0,
            fontSize: 16,
            fontLine: 1.5,
            isRe: false,
        }
    },
    mounted() {

    },
    created() {

        this.init();
        this.getComboInit();


    },

    methods: {
        PopoverHide() {
            // 重新进入页面
            if (this.isRe) {
                this.$router.go(0)
            }
        },
        fontSizeChange(e) {
            this.isRe = true
            localStorage.setItem('fontSize', e)
        },
        fontLineChange(e) {
            this.isRe = true
            localStorage.setItem('fontLine', e)
        },
        setUserCookie(type, value) {
            if (type == 'isRead') {
                console.log(this.isRead, value)
                localStorage.setItem('isRead', value)
            }
        },
        setSpeed(e) {
            console.log(e)
            switch (e) {
                case '慢速':
                    this.speed = '慢速'
                    localStorage.setItem('tts_speed', -1)
                    break;
                case '正常':
                    this.speed = '正常'
                    localStorage.setItem('tts_speed', 0)
                    break;
                case '快速':
                    this.speed = '快速'
                    localStorage.setItem('tts_speed', 1)
                    break;
                case '极速':
                    this.speed = '极速'
                    localStorage.setItem('tts_speed', 2)
                    break;
                case '-1':
                    this.speed = '慢速'
                    localStorage.setItem('tts_speed', -1)
                    break;
                case '0':
                    this.speed = '正常'
                    localStorage.setItem('tts_speed', 0)
                    break;
                case '1':
                    this.speed = '快速'
                    localStorage.setItem('tts_speed', 1)
                    break;
                case '2':
                    this.speed = '极速'
                    localStorage.setItem('tts_speed', 2)
                    break;
                default:
                    this.speed = '正常'
                    localStorage.setItem('tts_speed', 0)
                    break;

                    console.log(this.speed)
            }
        },
        setData() {
            localStorage.setItem('openId', '')
            localStorage.setItem('deptId', '')
            this.$message.warning('退出成功！')
            window.location.href = window.location.origin + '/app'

        },
        async init() {
            // console.log("init", localStorage.getItem('isRead'))
            this.setSpeed(localStorage.getItem('tts_speed'))
            this.isRead = localStorage.getItem('isRead') == 'false' ? false : true
            this.fontSize = localStorage.getItem('fontSize') ? parseInt(localStorage.getItem('fontSize')) : 16
            this.fontLine = localStorage.getItem('fontLine') ? parseFloat(localStorage.getItem('fontLine')).toFixed(1) : 1.5
            console.log("localStorage.getItem('CustomerInfo')", localStorage.getItem('CustomerInfo'))

            localStorage.getItem('CustomerInfo') && (this.CustomerInfo = JSON.parse(localStorage.getItem('CustomerInfo')));
            console.log("CustomerInfo", this.CustomerInfo)
            localStorage.getItem('userInfo') && (this.quesCarry = JSON.parse(localStorage.getItem('userInfo')));
            console.log("init", this.quesCarry)
            if (this.quesCarry.first == "") {

                listAiHotNoScope().then(res => {
                    let data = res.rows
                    if (data.length > 0) {
                        console.log("hotQues", data)
                        this.hotQuesList = data
                    }
                })



                await listAILibrary().then(res => {
                    let data = res.data
                    if (data.length > 0) {
                        data.map(item => {
                            if (item["图片"]) {
                                item["图片"] = this.baseApi + item["图片"]
                                this.anli.push(item)
                            }
                        })
                    }
                })
                console.log("anli", this.anli)

                await listZhProduct().then(res => {
                    let data = res.data
                    if (data.length > 0) {
                        data.forEach(item => {
                            console.log("item", item.category)
                            if (item['产品分类'] == "院护产品") {
                                // console.log("listProduct",this.proYuanhu,this.quesCarry)
                                this.proYuanhu.push(item)
                            } else {
                                this.proJiaju.push(item)
                            }
                        })
                    }
                })

                await listZhCertification().then(res => {
                    let data = res.data
                    if (data.length > 0) {
                        data.forEach(item => {
                            this.auth.push(item)
                        })
                    }
                })

                await listZhCombo().then(res => {
                    let data = res.data
                    if (data.length > 0) {
                        data.forEach(item => {
                            this.cuxiao.push(item)
                        })
                    }
                })
                console.log("CustomerInfo", this.CustomerInfo)
                await listZhHistory({ openId: this.CustomerInfo.openId }).then(res => {
                    let data = res.data
                    if (data.length > 0) {
                        data.forEach(item => {
                            this.history.push(item)
                        })
                    }
                })
                // [{ "purchaseType": "0", "comboId": "2", "productId": null, "purchaseNum": 2 }, { "purchaseType": "1", "comboId": null, "productId": "14", "purchaseNum": 5 }]
                let str = `
                产品信息：【产品库（严格基于此推荐，不可虚构或添加）（特殊字段说明：priorityRecommendation==1时优先推荐）、\n
                （一）院护产品（高价值款，优先用于超预算推荐，需去美容院操作）${JSON.stringify(this.proYuanhu)}、\n
                （二）家居产品（基础款，优先用于预算内推荐，可自主在家使用）${JSON.stringify(this.proJiaju)}】、\n
                权威认证：【（产品信息中的authId关联权威认证id，推荐产品时同步想客户发送权威认证，体现产品的正规和安全有效）${JSON.stringify(this.auth)}】、\n
                促销活动：【（自然融入推荐，不可强行推销，需明确活动细节）${JSON.stringify(this.cuxiao)}】、\n
                真实案例：【${JSON.stringify(this.anli)}】、\n
                历史购买：【（根据历史购买记录，可推荐客户购买过产品，可结合产品信息中的authId关联权威认证id，推荐产品时同步想客户发送权威认证，体现产品的正规和安全有效）${JSON.stringify(this.history)}）】、\n
                `;
                // this.quesCarry.first = '1111';
                this.quesCarry.first = str;
            }
            if (this.quesCarry.always == "") {
                let res = this.CustomerInfo
                res.name = res.name || res.nickName
                let str = `【用户信息：姓名：${res.name}，微信昵称：${res.nickName}，年龄：${res.age}、身高：${res.height}、体重：${res.weight}、附加信息：${res.remark}】`;
                console.log("携带的用户信息：", str)
                this.quesCarry.always = str;

            }
            getManageKey('agent.def.id').then(response => {
                if (response.code == 200 && response.rows && response.rows.length > 0) {
                    const data = JSON.parse(response.rows[0].value) ? JSON.parse(response.rows[0].value) : null
                    if (data) {
                        this.agentId = data.agent.key ? data.agent.key : ""
                        console.log("this.agentId", this.agentId)
                    }
                }
            });
        },
        getComboInit() {
            listComboByArticleId(localStorage.getItem("postId")).then(res => {
                if (res.code == 200) {
                    let data = res.data;

                    // 根据返回数据填充productInfo
                    this.productInfo = {
                        id: data.id,
                        name: data.name,
                        description: data.introduction,
                        image: this.baseApi + data.image,
                        originalPrice: data.price,
                        currentPrice: data.price,
                        stock: data.num,
                        gifts: data.freeGiftList ? data.freeGiftList.map(gift => gift.product.name) : [],
                    };

                    // // 根据返回数据填充productItems
                    this.productItems = data.productList ? data.productList.map(item => ({
                        id: item.product.id,
                        name: item.product.name,
                        specs: item.product.specification,
                        price: item.product.price,
                        image: this.baseApi + item.product.image, // 数据中未提供图片字段
                        num: item.num
                    })) : [];

                }
            });
        },

        upQuote(e) {
            this.productInfo = {};
            this.productItems = [];
            if (e.CID) {
                this.getCombo(e);
            } else {
                this.getProduct(e.PID);
            }
        },
        addClickHotQues(e) {
            updateAiHot({ id: e.id, clickCount: e.clickCount }).then(res => {
                console.log("updateAiHot", res)
            })
        },
        getCombo(e) {
            console.log("upProduct", e) // e={CID:"1",PID:"1,2,3"}
            getCombo(e.CID).then(res => {
                if (res.code == 200 && res.data) {
                    let data = res.data;
                    console.log("getCombo", data)
                    // 根据返回数据填充productItems
                    this.productInfo = data ? {
                        id: data.id,
                        name: data.name,
                        description: data.introduction,
                        image: this.baseApi + data.image,
                        originalPrice: data.price,
                        currentPrice: data.price,
                        stock: data.num,
                        gifts: data.freeGiftList ? data.freeGiftList.map(gift => gift.product.name) : [],
                    } : [];

                    // "comboProduct": "[{\"productId\":\"6\",\"num\":1},{\"productId\":\"7\",\"num\":1},{\"productId\":\"10\",\"num\":1}]",
                    const PID = data.comboProduct ? JSON.parse(data.comboProduct).map(item => item.productId).join(",") : "";
                    console.log("PID", PID)
                    this.getProduct(PID);
                }
                console.log("this.productInfo", this.productInfo)
            });
        },
        getProduct(PID) {
            const PIDARR = PID.split(",")
            for (let i = 0; i < PIDARR.length; i++) {
                getProduct(PIDARR[i]).then(res => {
                    if (res.code == 200) {

                        let data = res.data;
                        console.log("getProduct", data)
                        // 根据返回数据填充productItems
                        this.productItems.push({
                            id: data.id,
                            name: data.name,
                            specs: data.specification,
                            price: data.price,
                            image: this.baseApi + data.image, // 数据中未提供图片字段
                        })

                    }
                    console.log("this.productItems", this.productItems)
                })

            }
        },
        upLocalUserInfo() {
            // 打开抽屉，弹窗内有两个多行文本输入框，1.（第一次提问携带信息）2.（需要一直携带的信息）
            this.drawerVisible = true;
        },
        saveUserInfo() {
            // 保存用户信息逻辑
            console.log('首次提问信息:', this.quesCarry.first);
            console.log('持续携带信息:', this.quesCarry.always);
            localStorage.setItem('userInfo', JSON.stringify(this.quesCarry));
            this.drawerVisible = false;
        },
        upUserInfo() {
            localStorage.setItem("userInfo", "")
            // 刷新页面刷新
            location.reload()
        }
    },

}
</script>

<style>
/* 主题颜色定义 */
:root {
    --color-primary: #8a5a52;
    /* 深棕主色 */
    --color-secondary: #d4b4a4;
    /* 浅棕辅助色 */
    --color-accent: #f5e8e4;

    --color-bg-right: #f9f3ed;
    /* 右侧区域背景 */
    --font-serif: 'Playfair Display', Georgia, serif;
    /* 优雅衬线字体 */
}

/* 美化弹窗样式 */
.beauty-dialog .el-dialog {
    border-radius: 16px !important;
    overflow: hidden;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important;
}

.beauty-dialog .el-dialog__header {
    display: none;
}
</style>
<style scoped lang="scss">
@media (min-width: 1500px) {
    #app {
        max-width: 1000px;
        margin: 0 auto;
    }
}

/* 引入Tailwind CSS变量和工具类 */
@layer utilities {
    .content-auto {
        content-visibility: auto;
    }

    .smooth-transition {
        transition: all 0.3s ease-in-out;
    }
}

/* 对话气泡样式 */
.chat-bubble-left {
    background-color: white;
    border-radius: 1rem;
    border-bottom-left-radius: 0.25rem;
}

.chat-bubble-right {
    background-color: var(--color-primary);
    color: white;
    border-radius: 1rem;
    border-bottom-right-radius: 0.25rem;
}

/* 颜色类 */
.text-primary {
    color: var(--color-primary);
}

.text-secondary {
    color: var(--color-secondary);
}

.bg-bg-right {
    width: 100%;
    height: 100vh;
    background-color: var(--color-bg-right);
    background-image:
        linear-gradient(0deg, rgba(0, 0, 0, 0.03) 1px, transparent 1px),
        linear-gradient(90deg, rgba(0, 0, 0, 0.03) 1px, transparent 1px);
    background-size: 20px 20px;
}

.wendaItem {
    width: 100%;
    height: calc(100vh - 60px);
    position: relative;
    bottom: 0;
    left: 0;
    right: 0;
}

.ProductQuote {
    position: fixed;
    top: 0;
    left: 0;
    right: 50%;
    z-index: 50;
}
</style>
